package com.smarteye.mpu;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;



public class HistoryDatabase extends SQLiteOpenHelper {
	private static final String name = "history_mpu";
	private static final int version = 1;
	private SQLiteDatabase db;

	public HistoryDatabase(Context context) {
		super(context, name, null, version);
		db = getWritableDatabase();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE IF NOT EXISTS history_mpu (serveraddr varchar(32), serverport varchar(32))");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	public void insert(LoginParam info) {
		delete(info);
		ContentValues c = new ContentValues();
		c.put("serveraddr", info.getServerAddr());
		c.put("serverport", info.getServerPort());
		db.insert("history_mpu ", null, c);
	}

	public void deleteAll() {
		db.delete("history_mpu", null, null);
	}

	public void delete(LoginParam param) {
		db.delete("history_mpu", "serveraddr=? and serverport=?", new String[] {
				param.getServerAddr(), param.getServerPort() });
	}

	public ArrayList<LoginParam> getAllLoginParam() {
		ArrayList<LoginParam> loginInfos = new ArrayList<LoginParam>();
		Cursor cursor = db.rawQuery("select * from history_mpu", null);
		while (cursor.moveToNext()) {
			String serverAddr = cursor.getString(0);
			String serverPort = cursor.getString(1);

			LoginParam loginInfo = new LoginParam();
			loginInfo.setServerAddr(serverAddr);
			loginInfo.setServerPort(serverPort);
			loginInfos.add(loginInfo);
		}
		cursor.close();
		return loginInfos;
	}

	public void close() {
		db.close();
	}
}